﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;

namespace WeChat
{
    public partial class VerificationCodes : System.Web.UI.Page
    {
        //创建验证码
        protected void Page_Load(object sender, EventArgs e)
        {
            string validateCode = CreateRegionCode(4);
            Session["validatecode"] = validateCode;
            this.CreateCheckCodeImage(validateCode);
        }

        public string CreateRegionCode(int strlength)
        {
            string so = "1,2,3,4,5,6,7,8,9,0";
            string[] strArr = so.Split(',');
            string code = "";
            Random rand = new Random();
            for (int i = 0; i < strlength; i++)
            {
                code += strArr[rand.Next(0, strArr.Length)];
            }
            return code;
        }

        private void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(65, 24);
            Graphics g = Graphics.FromImage(image);

            //random number
            Random random = new Random();

            g.Clear(Color.Linen);

            Font font = new System.Drawing.Font("Arial", 17, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(30, 0, image.Width, image.Height), Color.Coral, Color.Green, 1.2f, true);
            g.DrawString(checkCode, font, brush, 1, 2);

            for (int i = 0; i < 5; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            g.DrawRectangle(new Pen(Color.OldLace), 0, 0, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }

    }
}
